<?php
/**
 * Created by 七月.
 * Author: 七月
 * 微信公号：小楼昨夜又秋风
 * 知乎ID: 七月在夏天
 * Date: 2017/2/26
 * Time: 14:15
 */

namespace app\api\controller\v1;

use app\api\controller\BaseController;
use app\api\service\MallSetup;
use app\api\service\Pay as PayService;
use app\api\service\WxConfig;
use app\api\service\WxNotify;
use app\api\validate\IDMustBePositiveInt;
use think\Controller;

class Pay extends BaseController
{
    protected $beforeActionList = [
        'checkExclusiveScope' => ['only' => 'getPreOrder']
    ];
    /**
     * 返回来去微信支付参数
     * @param string $id
     * @return \think\response\Json
     */
    public function getPreOrder($id='')
    {
        (new IDMustBePositiveInt()) -> goCheck();
        $pay= new PayService($id);
        return json($pay->pay());
    }
    /**
     * 微信支付回调处理
     */
    public function receiveNotify()
    {
        $xml = file_get_contents('php://input');//接收微信支付回调通知并验证签名是否正确
        $data = $this->FromXml($xml);
        error_log(print_r($data, 1), 3, "./yzh.txt");
        //获取商城设置
        $service = new MallSetup();
        $appid = $data['appid'];
        $mallInfo =$service->getMallByAppid($appid);
        $mch_id = $data['mch_id'];
        //验证签名信息，并返回成功或失败
        $config = new WxConfig($appid,$mch_id,$mallInfo->key);
        $notify = new WxNotify();
        $notify->Handle($config);
    }
    /**
     * xmlToarray
     * @param $xml
     * @return mixed
     */
    private  function FromXml($xml)
    {
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $data;
    }
    
}